package pers.qianyu.month_202012.date_20201217;

/**
 * 1011. 在 D 天内送达包裹的能力
 * https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days/
 *
 * @author mizzle rain
 * @date 2020-12-17 22:49
 */
public class ShipWithinDays {
    // 注意不要排序，会打乱原来数组的顺序
    public int shipWithinDays(int[] weights, int D) {
        int sum = 0;
        int max = 0;
        for (int weight : weights) {
            sum += weight;
            max = Math.max(max, weight);
        }
        int left = max, right = sum;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (isValid(weights, mid, D)) {
                right = mid - 1;
            } else {
                left = left + 1;
            }
        }
        return right + 1;
    }

    private boolean isValid(int[] weights, int K, int D) {
        int sum = 0;
        int count = 0;
        for (int i = 0; i < weights.length; i++) {
            int weight = weights[i];
            sum += weight;
            if (sum > K) {
                i--;
                sum = 0;
                count++;
            }
        }
        if (sum != 0) {
            count++;
        }
        return count <= D;
    }

    public static void main(String[] args) {
        ShipWithinDays ship = new ShipWithinDays();
        //boolean valid = ship.isValid(new int[]{3, 2, 2, 4, 1, 4}, 6, 3);
        int result = ship.shipWithinDays(new int[]{3, 2, 2, 4, 1, 4}, 3);
        System.out.println("result = " + result);
    }
}
